package com.df.managers;
import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.df.page.PagerModel;
import com.df.page.SystemContext;
public class AbstractManager extends HibernateDaoSupport {
    public PagerModel searchPaginated(String hql, String s) {
        return searchPaginated(hql, null, SystemContext.getOffset(), SystemContext.getPagesize(), s);
    }
    public PagerModel searchPaginated(String hql) {
        return searchPaginated(hql, null, SystemContext.getOffset(), SystemContext.getPagesize(), "1");
    }
    public PagerModel searchPaginated(String hql, Object[] params) {
        return searchPaginated(hql, params, SystemContext.getOffset(), SystemContext.getPagesize(), "1");
    }
    public PagerModel searchPaginated(String hql, Object param) {
        return searchPaginated(hql, new Object[] { param }, SystemContext.getOffset(), SystemContext.getPagesize(), "1");
    }
    /**
     * @param hql
     * @param params
     * @param offset
     * @param pagesize
     * @return
     */
    public PagerModel searchPaginated(String hql, Object[] params, int offset, int pagesize, String s) {
        // 锟杰硷拷录锟斤拷
        String countHql = getCountQuery(hql);
        
        Query query = this.getSession().createQuery(countHql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i, params[i]);
            }
        }
        int total = ((Long) query.uniqueResult()).intValue();
        // 锟斤拷锟�
        if (!"1".equals(s)) {
            hql += s;
        }
        query = this.getSession().createQuery(hql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i, params[i]);
            }
        }
        query.setFirstResult(offset).setMaxResults(pagesize);
        List datas = query.list();
        PagerModel pm = new PagerModel();
        pm.setDatas(datas);
        pm.setTotal(total);
        return pm;
    }
    /**
     * 锟斤拷莞锟斤拷hql 锟矫碉拷锟斤拷汛锟杰硷拷录锟斤拷锟�hql select ... from Orgniazation o where o.parent is
     * null 锟矫碉拷 select count(*) from Orgniazation o where o.parent is null
     * @param sql
     * @return
     */
    public String getCountQuery(String sql) {
        int index = sql.indexOf("from");
        if (index != -1) {
            return "select count(*)" + sql.substring(index);
        }
        throw new RuntimeException("锟斤拷锟斤拷锟絪ql锟斤拷锟�");
    }
}
